<?php

/**
 * 加解密类
 */

namespace framework\extend;
use framework\extend\Session;

class Encrypter {

	/**
	 * 生成UUID
	 * @param  string $value 待解密字符串
	 * @return string
	 */
	public function getId() {
        if (function_exists('uuid_create') && !function_exists('uuid_make')) {
            $id = uuid_create(UUID_TYPE_DEFAULT);
        } elseif (function_exists('com_create_guid')) {
            $id = strtolower(trim(com_create_guid(), '{}'));
        } else {
            $id = $this->createId();
        }
        return $id;
    }

    /**
     * 创建UUID
     * @return string
     */
    protected function createId() {
        $salt = substr(hash('sha256', microtime(true) . mt_rand()), 0, 64);
        $hex  = substr(hash('sha256', $salt), 0, 32);
        $time_low = substr($hex, 0, 8);
        $time_mid = substr($hex, 8, 4);
        $time_hi_and_version = base_convert(substr($hex, 12, 4), 16, 10);
        $time_hi_and_version &= 0x0FFF;
        $time_hi_and_version |= (4 << 12);
        $clock_seq_hi_and_reserved = base_convert(substr($hex, 16, 4), 16, 10);
        $clock_seq_hi_and_reserved &= 0x3F;
        $clock_seq_hi_and_reserved |= 0x80;
        $clock_seq_low = substr($hex, 20, 2);
        $nodes = substr($hex, 20);
        $uuid  = sprintf('%s-%s-%04x-%02x%02x-%s',
                    $time_low, $time_mid,
                    $time_hi_and_version, $clock_seq_hi_and_reserved,
                    $clock_seq_low, $nodes
                );

        return $uuid;
    }

    /**
     * 验证是否符合uuid规范
     */
    public function isId($uuid) {
        return preg_match("/^[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}$/", $uuid);
    }


    /**
     * 生成一个表单token
     * @return array
     */
    public function enFormToken($session = false) {
        $stamp = time();
        $token = md5(strrev($stamp).$stamp);
        $data = array('token'=>$token, 'stamp'=>$stamp);
        $Session  = new Session('token');
        $Session->set($data);
        return $data;
    }

    /**
     * 验证Token
     * @param $stamp
     * @param $token
     * @param int $time
     * @param bool $session  //防止表单重复提交
     * @return bool
     */
    public function deFormToken($stamp, $token, $time = 0,$session = false) {
        $Session  = new Session('token');
        $token_key = $Session->get()['token'];
        $Session->del();
        if ($time && abs(time()-(int)$stamp) > $time) {
            return false;
        }
        $value = md5(strrev($stamp).$stamp);
        if ($token == $value){
            if($session){
                if($token_key == $token){
                    session_unset('token');
                    unset($_SESSION['token']);
                    return  true;
                }
                return false;
            }
            return  true;
        }
        return false;
    }
}
